<template>
  <view>
    <view class="container">
      <view class="ui-all">
        <view class="ui-list" :data-bledevice="printerInfo" @tap="handleBindBluetoothDevice">
          <text style="width: 150rpx;">{{ $t('pages.sys.profile.printerInfoText') }}</text>
          <view class="icon">
            <image :src="printerInfoImg"></image>
          </view>
          <view class="text">
            <view class="title">{{ printerInfo.name }}</view>
            <view class="sub-title">{{ printerInfo.deviceId }}</view>
          </view>
          <image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
        </view>

        <view class="ui-input">
          <text style="width: 150rpx;">{{ $t('pages.sys.profile.printerPaperSizeText') }}</text>
          <text style="width: 130rpx;text-align: right;">{{ $t('pages.sys.profile.printerPaperSizeWidthText') }}</text>
          <input type="number" v-model="paperSize.Width" @blur="handleSetPaperSize" />
          <text style="width: 130rpx;text-align: right;">{{ $t('pages.sys.profile.printerPaperSizeHeightText') }}</text>
          <input type="number" v-model="paperSize.Height" @blur="handleSetPaperSize" />
        </view>
        <view class="ui-input">
          <text style="width: 150rpx;">{{ $t('pages.sys.profile.printerPaperGapText') }}</text>
          <text style="width: 130rpx;text-align: right;">{{ $t('pages.sys.profile.printerPaperGapSpaceText') }}</text>
          <input type="number" v-model="paperGap.M" @blur="handleSetPaperGap" />
          <text style="width: 130rpx;text-align: right;">{{ $t('pages.sys.profile.printerPaperGapOffsetText') }}</text>
          <input type="number" v-model="paperGap.N" @blur="handleSetPaperGap" />
        </view>
        <view class="ui-input">
          <text style="width: 150rpx;">{{ $t('pages.sys.profile.printerPaperBlineText') }}</text>
          <text
            style="width: 130rpx;text-align: right;">{{ $t('pages.sys.profile.printerPaperBlineHeightText') }}</text>
          <input type="number" v-model="paperBline.M" @blur="handleSetPaperBline" />
          <text
            style="width: 130rpx;text-align: right;">{{ $t('pages.sys.profile.printerPaperBlineOffsetText') }}</text>
          <input type="number" v-model="paperBline.N" @blur="handleSetPaperBline" />
        </view>

        <view class="ui-button">
          <button type="primary" :loading="isBluetoothSearching"
            @click="handleStartSearch">{{ $t('pages.sys.profile.printerBleStartSearchText') }}</button>
          <button type="warn" @click="handleStopSearch">{{ $t('pages.sys.profile.printerBleStopSearchText') }}</button>
          <button type="primary" :loading="isPrinting" style="background: #18BC37;" :disabled="!printerConnected"
            @click="handlePrintTest">
            {{ $t('pages.sys.profile.printerPrintTestText') }}
          </button>
        </view>
      </view>

    </view>
    <view class="list-content">
      <view class="list">
        <view class="li" v-for="(item) in bleSearchList" :data-title="item.deviceId" :data-name="item.name"
          :data-advertisData="item.advertisServiceUUIDs" :key="item.deviceId" :data-bledevice="item"
          @tap="handleBindBluetoothDevice">
          <view class="icon">
            <image :src="item.deviceId === printerInfo.deviceId ? printerInfoImg : bluetoothSearchingImg"></image>
          </view>
          <view class="text">
            <view class="title">{{ item.name }}</view>
            <view class="sub-title">{{ item.deviceId }}</view>
            <!-- <view class="sub-title">{{ item.RSSI }}</view> -->
          </view>
          <image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
        </view>
      </view>

    </view>

    <view style="margin-top: 80rpx;" />
  </view>
</template>

<script>
  import bluetoothImg from '@/static/images/app/bluetooth@128x.png';
  import bluetoothConnectedImg from '@/static/images/app/bluetooth_connected@128x.png';
  import bluetoothDisabledImg from '@/static/images/app/bluetooth_disabled@128x.png';
  import bluetoothSearchingImg from '@/static/images/app/bluetooth_searching@128x.png';
  import {
    createPrintCommand,
    sendPrintCommand,
  } from '@/utils/printer/index';
  import {
    isString,
    isMacAddress
  } from "@/utils/is";
  import {
    useScan
  } from "@/utils/scan-code";
  const {
    scan
  } = useScan();
  export default {
    data() {
      return {
        /** 打印机纸张尺寸(mm) */
        paperSize: {
          Width: 0,
          Height: 0
        },
        /** 打印机纸张间距(mm) */
        paperGap: {
          M: 0,
          N: 0
        },
        /** 打印机纸张黑标(mm) */
        paperBline: {
          M: 0,
          N: 0
        },
        /** 是否正在打印中 */
        isPrinting: false,
        /** 蓝牙搜索列表 */
        bleSearchList: [],
        bluetoothImg,
        bluetoothConnectedImg,
        bluetoothDisabledImg,
        bluetoothSearchingImg,
      }
    },
    computed: {
      printerInfo() {
        const that = this;
        return that.$store.getters.getPrinterInfo;
      },
      printerInfoImg() {
        const that = this;
        if (that.$store.getters.getPrinterInfo === undefined || that.$store.getters.getPrinterInfo === null ||
          that.$store.getters.getPrinterInfo.deviceId === undefined || that.$store.getters.getPrinterInfo.deviceId ===
          null ||
          that.$store.getters.getPrinterInfo.deviceId === '') {
          return '';
        }
        if (that.$store.getters.getPrinterInfo.connected === true) {
          return bluetoothConnectedImg;
        }
        return bluetoothDisabledImg;
      },
      printerConnected() {
        const that = this;
        if (that.$store.getters.getPrinterInfo.connected === true) {
          return true;
        }
        return false;
      },
      isBluetoothOpened() {
        const that = this;
        if (that.$store.getters.getBluetoothOpened === true) {
          return true;
        }
        return false;
      },
      isBluetoothSearching() {
        const that = this;
        if (that.$store.getters.getBluetoothSearching === true) {
          return true;
        }
        return false;
      }
    },
    async onShow() {
      const that = this;
      // 导航栏多语言
      uni.setNavigationBarTitle({
        title: that.$t('pages.sys.profile.printerSetupText')
      });
      // 打印纸张
      that.paperSize = that.$store.getters.getPrinterPaperSize;
      that.paperGap = that.$store.getters.getPrinterPaperGap;
      that.paperBline = that.$store.getters.getPrinterPaperBline;

      // 监听扫描
      scan.start(async (res) => {
        // console.log('扫描结果', res);
        await that.scanHandler({
          data: res.data
        });
      });
    },
    destroyed: function() {
      // uni.showModal({
      //     title: 'destroyed',
      //     content: '停止监听扫描'
      // });
      // 页面退出时一定要停止监听扫描,否则监听将一直有效
      scan.stop();
    },
    onNavigationBarButtonTap(e) {
      const that = this;
      // console.log("点击了自定义按钮", e);
      if (e.index === 0) {
        uni.scanCode({
          success: async function(res) {
            // console.log('类型', res.scanType);
            // console.log('内容', res.result);
            await that.scanHandler({
              data: res.result
            });
          }
        });
      }
    },
    methods: {
      /** 扫描处理器 */
      async scanHandler(res) {
        const that = this;
        const data = res.data;
        const tmpData = data.replace(/'/g, '"');
        const scanData = JSON.parse(tmpData);
        if (!scanData.Type || scanData.Type.toLowerCase() !== 'bleprinter' || !scanData.Data) {
          return;
        }
        const qrPrinterInfo = scanData.Data;
        if (qrPrinterInfo) {
          // 连接蓝牙打印机
          await that.connectBluetoothDevice(qrPrinterInfo);
        }
      },
      /** 处理设置纸张尺寸 */
      async handleSetPaperSize() {
        const that = this;
        await that.$store.dispatch('setPrinterPaperSize', that.paperSize);
      },
      /** 处理设置纸张间距 */
      async handleSetPaperGap() {
        const that = this;
        await that.$store.dispatch('setPrinterPaperGap', that.paperGap);
      },
      /** 处理设置纸张黑标 */
      async handleSetPaperBline() {
        const that = this;
        await that.$store.dispatch('setPrinterPaperBline', that.paperBline);
      },
      /** 处理开始搜索蓝牙设备 */
      async handleStartSearch() {
        const that = this;
        await that.$store.dispatch('startBluetoothSearch', {
          callback: async (res) => {
            // console.log('startBluetoothSearch_callback', res);
            that.bleSearchList = res;
          },
          mode: 'modal'
        });
      },
      /** 处理停止搜索蓝牙设备 */
      async handleStopSearch() {
        const that = this;
        await that.$store.dispatch('stopBluetoothSearch', 'modal');
      },
      /** 处理绑定蓝牙设备 */
      async handleBindBluetoothDevice(e) {
        const that = this;
        // uni.showModal({
        // 	title: '处理绑定蓝牙设备',
        // 	content: JSON.stringify(e)
        // });
        const bleDevice = e.currentTarget.dataset.bledevice;
        await that.connectBluetoothDevice(bleDevice);
      },
      /** 链接蓝牙设备 */
      async connectBluetoothDevice(bleDevice) {
        const that = this;
        // uni.showModal({
        // 	title: '链接蓝牙设备',
        // 	content: JSON.stringify(bleDevice)
        // });
        try {
          uni.showLoading({
            title: that.$t('common.loadingText'),
            mask: true
          });

          that.handleStopSearch();

          if (that.printerInfo.deviceId === bleDevice.deviceId && that.printerInfo.connected === true) {
            await that.$store.dispatch('disconnectBlePrinter', {
              deviceId: bleDevice.deviceId,
              mode: 'modal'
            });
          } else {
            const connected = await that.$store.dispatch('connectBlePrinter', {
              printerInfo: bleDevice,
              timeout: null,
              mode: 'modal'
            });
            if (connected) {
              // uni.showModal({
              // 	title: '特征值',
              // 	content: JSON.stringify(that.printerInfo)
              // });
              uni.hideLoading();
              uni.showToast({
                icon: 'success',
                title: this.$t('common.successText'),
                mask: true
              });
            }
          }
          uni.hideLoading();
        } catch (err) {} finally {
          uni.hideLoading();
        }
      },
      /** 处理打印测试 */
      async handlePrintTest() {
        const that = this;

        that.isPrinting = true;
        try {
          const printerInfo = that.printerInfo;
          const storagePrinterInfo = {
            name: printerInfo.name, // (String 类型 )蓝牙设备名称 某些设备可能没有此字段值。
            deviceId: printerInfo.deviceId //  (String 类型 )蓝牙设备的id
            // advertisData: printerInfo.advertisData, //  (ArrayBuffer 类型 )蓝牙设备的广播数据段中的ManufacturerData数据段
            // advertisServiceUUIDs: printerInfo.advertisServiceUUIDs, //  (Array[String] 类型 )蓝牙设备的广播数据段中的ServiceUUIDs数据段
            // localName: printerInfo.localName, //  (String 类型 )蓝牙设备的广播数据段中的LocalName数据段
            // serviceData: printerInfo.serviceData //  (JSON 类型 )蓝牙设备的广播数据段中的ServiceData数据段
          };
          // const printerQR = `{ \'Type\': \'bleprinter\', \'Data\': { \'name\': \'${printerInfo.name}\', \'deviceId\': \'${printerInfo.deviceId}\'}}`;
          const printerObj = {
            Type: "bleprinter",
            Data: storagePrinterInfo
          };
          // 花引号替换为直引号
          const printerQR = JSON.stringify(printerObj).replace(/"([^"]*)"/g, "'$1'");

          let command = createPrintCommand();
          command.text(`${that.$t('pages.sys.profile.printerInfoText')}：${printerInfo.name}`, 0, 20); // 打印机名称
          // command.text(`标识：${printerInfo.deviceId}`, 0, 60);	// 打印机设备标识
          command.barCode(printerInfo.deviceId, 5, 50); //打印机设备标识条码
          command.qrCode(printerQR, 5, 150); //打印机信息二维码

          command.text(
            `${that.$t('pages.sys.profile.printerPaperSizeText')}：${that.$t('pages.sys.profile.printerPaperSizeWidthText')} ${that.paperSize.Width} ${that.$t('pages.sys.profile.printerPaperSizeHeightText')} ${that.paperSize.Height}`,
            220, 180); // 尺寸
          command.text(
            `${that.$t('pages.sys.profile.printerPaperGapText')}：${that.$t('pages.sys.profile.printerPaperGapSpaceText')} ${that.paperGap.M} ${that.$t('pages.sys.profile.printerPaperGapOffsetText')} ${that.paperGap.N}`,
            220, 230); // 间距
          command.text(
            `${that.$t('pages.sys.profile.printerPaperBlineText')}：${that.$t('pages.sys.profile.printerPaperBlineHeightText')} ${that.paperBline.M} ${that.$t('pages.sys.profile.printerPaperBlineOffsetText')} ${that.paperBline.N}`,
            220, 280); // 黑标

          sendPrintCommand(command, true, 'modal');

          that.isPrinting = false;
        } catch (err) {} finally {
          that.isPrinting = false;
        }
      }
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #f1f1f1 !important;
    font-size: 30upx !important;
  }

  .container {
    width: 100vw;
    background: #fff;
  }

  .ui-all {
    // padding: 20rpx 40rpx;

    .ui-list {
      width: 100%;
      // text-align: left;
      // height: 140rpx;
      padding: 10rpx 0;
      border-bottom: 1px solid rgb(243, 243, 243);
      display: flex;
      align-items: center;

      &:last-child {
        border: none;
      }

      .icon {
        flex-shrink: 0;
        width: 50upx;
        height: 50upx;

        image {
          width: 50upx;
          height: 50upx;
        }
      }

      .text {
        padding-left: 20upx;
        width: 100%;

        .title {
          // color: #666;
        }

        .sub-title {
          // margin-top: 1upx;
          color: #5c5f66;
          font-style: oblique;
          // font-size: 20upx;
          // line-height: 26upx;
        }
      }

      .to {
        flex-shrink: 0;
        width: 40upx;
        height: 40upx;
      }

      text {
        display: inline-block;
        color: #4a4a4a;
        font-size: 28rpx;
      }
    }

    .ui-list:active {
      background-color: #f8f8f8;
    }

    .ui-input {
      width: 100%;
      padding: 10rpx 0;
      border-bottom: 1px solid rgb(243, 243, 243);
      display: flex;
      align-items: center;

      &:last-child {
        border: none;
      }

      text {
        display: inline-block;
        color: #4a4a4a;
        font-size: 28rpx;
      }

      input {
        color: #030303;
        width: 110rpx;
        padding: 0 15rpx 0 15rpx;
        font-size: 30rpx;
        display: inline-block;
        vertical-align: middle;
        border-bottom: 1px solid rgb(243, 243, 243);
      }
    }

    .ui-button {
      width: 100%;
      // height: 120rpx;
      padding: 30rpx 0;
      display: flex;
      align-items: center;
      border-bottom: 1px solid rgb(243, 243, 243);

      &:last-child {
        border: none;
      }

      button {
        font-size: 35rpx;
      }
    }
  }

  .list-content {
    background: #F2F6FC;
    margin-top: 2px;
  }

  .list {
    width: 100%;
    border-bottom: 15upx solid #f1f1f1;
    background: #F2F6FC;

    &:last-child {
      border: none;
    }

    .li {
      width: 92%;
      // height: 160upx;
      padding: 0 4%;
      border-bottom: 2px solid rgb(243, 243, 243);
      display: flex;
      align-items: center;

      &.noborder {
        border-bottom: 0
      }

      .icon {
        flex-shrink: 0;
        width: 50upx;
        height: 50upx;

        image {
          width: 50upx;
          height: 50upx;
        }
      }

      .text {
        padding-left: 20upx;
        width: 100%;

        .title {
          // color: #666;
        }

        .sub-title {
          // margin-top: 1upx;
          color: #5c5f66;
          font-style: oblique;
          // font-size: 20upx;
          // line-height: 26upx;
        }
      }

      .to {
        flex-shrink: 0;
        width: 40upx;
        height: 40upx;
      }
    }

    .li:active {
      background-color: #f8f8f8;
    }
  }
</style>
